<template>
    <div class="layout">
        <el-form
            ref="ruleFormRef"
            class="left_container zw-common-scrollbar"
            :model="formData"
            :rules="rules"
            label-width="73px">
            <div class="title">海报设置</div>
            <el-form-item label="标题" prop="title">
                <el-input
                    v-model="formData.title"
                    maxlength="15"
                    show-word-limit
                    placeholder="请输入标题名称"
                    clearable>
                </el-input>
            </el-form-item>
            <!-- 分组 -->
            <el-form-item label="分组" prop="group_id">
                <el-cascader
                    ref="cascaderRef"
                    v-model="formData.group_id"
                    style="width: 100%"
                    :options="groupData"
                    :props="defaultProps"
                    placeholder="请选择分组"
                    @change="orgChange" />
            </el-form-item>
            <el-form-item label="图片" prop="poster_config.imgUrl">
                <div class="upload-content">
                    <el-upload
                        v-if="!formData.poster_config.imgUrl"
                        :on-change="beforeAvatarUpload"
                        accept=".jpg,.jpeg,.png,.JPG,.JPEG"
                        :show-file-list="false"
                        :auto-upload="false">
                        <div class="upload-box">
                            <img src="@/assets/image/content/add-icon.png" alt="" />
                            <div>点击上传</div>
                        </div>
                    </el-upload>
                    <div v-else class="upload-file-box">
                        <el-icon class="del" color="#ffffff" size="20px" @click="delFile"><Delete /></el-icon>
                        <el-image style="width: 100%; height: 100%" :src="formData.poster_config.imgUrl" fit="cover" />
                    </div>
                    <div class="upload-text">图片支持JPG、PNG、JPEG格式，建议尺寸为1080*1920px，大小5M以内。</div>
                    <div class="upload-desc">没有合适的图片？<span @click="showTemplateBox">使用模板</span></div>
                </div>
            </el-form-item>
            <div class="title active">引流信息</div>
            <el-form-item label="活动二维码" class="codeLabel" prop="poster_config.codeUrl">
                <el-switch v-model="formData.poster_config.codeStatus" @change="changeQcodeStatusFun" />
            </el-form-item>
            <div v-if="formData.poster_config.codeStatus" class="code-choose-btn">
                <el-button @click="repeatChooseQcode">重新选择</el-button>
            </div>
            <el-form-item label="活动标题" label-width="87">
                <el-switch
                    v-model="formData.poster_config.codeDescInfo.titleInfo.status"
                    @change="
                        withOpenSwitch(() => handleChangeSwitch('titleInfo'), 'codeDescInfo.titleInfo.status')()
                    " />
            </el-form-item>
            <div v-if="formData.poster_config.codeDescInfo.titleInfo.status" class="codeText-set-box">
                <span class="config-label">颜色</span>
                <el-color-picker
                    v-model="formData.poster_config.codeDescInfo.titleInfo.color"
                    :predefine="predefineColors"
                    popper-class="poster-setting-color-picker" />
                <span class="config-label">大小</span>
                <el-select
                    v-model="formData.poster_config.codeDescInfo.titleInfo.fontSize"
                    style="width: 180px"
                    placeholder="全部">
                    <el-option v-for="item in fontOptions" :key="item" :label="item" :value="item">
                        {{ item }}
                    </el-option>
                </el-select>
            </div>
            <el-form-item
                v-if="formData.poster_config.codeDescInfo.titleInfo.status"
                label="标题"
                label-width="87"
                prop="poster_config.codeDescInfo.titleInfo.content"
                class="codeDescLabel">
                <el-input
                    v-model="formData.poster_config.codeDescInfo.titleInfo.content"
                    maxlength="15"
                    show-word-limit
                    placeholder="请输入标题"
                    clearable>
                </el-input>
            </el-form-item>

            <el-form-item label="活动描述" label-width="87">
                <el-switch
                    v-model="formData.poster_config.codeDescInfo.descInfo.status"
                    @change="withOpenSwitch(() => handleChangeSwitch('descInfo'), 'codeDescInfo.descInfo.status')()" />
            </el-form-item>
            <div v-if="formData.poster_config.codeDescInfo.descInfo.status" class="codeText-set-box">
                <span class="config-label">颜色</span>
                <el-color-picker
                    v-model="formData.poster_config.codeDescInfo.descInfo.color"
                    :predefine="predefineColors"
                    popper-class="poster-setting-color-picker" />
                <span class="config-label">大小</span>
                <el-select
                    v-model="formData.poster_config.codeDescInfo.descInfo.fontSize"
                    style="width: 180px"
                    placeholder="全部">
                    <el-option v-for="item in fontOptions" :key="item" :label="item" :value="item">
                        {{ item }}
                    </el-option>
                </el-select>
            </div>
            <el-form-item
                v-if="formData.poster_config.codeDescInfo.descInfo.status"
                prop="poster_config.codeDescInfo.descInfo.content"
                label="描述"
                class="codeDescLabel">
                <el-input
                    v-model="formData.poster_config.codeDescInfo.descInfo.content"
                    type="textarea"
                    maxlength="50"
                    show-word-limit
                    placeholder="请输入描述"
                    clearable>
                </el-input>
            </el-form-item>
        </el-form>
        <div class="right_container">
            <div class="phone-content zw-common-scrollbar">
                <div class="poster-box" :style="posterBoxStyle">
                    <div v-if="formData.poster_config.imgUrl" id="posterBox" ref="containerRef" class="poster-item">
                        <img
                            :src="formData.poster_config.imgUrl"
                            draggable="false"
                            class="posterImg"
                            @load="handlePosterBackgroundImg" />
                        <div
                            v-if="formData.poster_config.codeUrl && formData.poster_config.codeStatus"
                            ref="qrcode"
                            class="code-box"
                            :style="{ top: formData.poster_config.y + 'px', left: formData.poster_config.x + 'px' }"
                            @mousedown.stop.capture="moveStart">
                            <img :src="codeImgUrl" draggable="false" alt="" />
                        </div>
                        <div
                            v-if="formData.poster_config.codeDescInfo.titleInfo.status"
                            ref="title"
                            :style="{
                                color: formData.poster_config.codeDescInfo.titleInfo.color,
                                'font-size': formData.poster_config.codeDescInfo.titleInfo.fontSize + 'px',
                                top: formData.poster_config.title_y + 'px',
                                left: formData.poster_config.title_x + 'px'
                            }"
                            class="title"
                            @mousedown.stop.capture="moveStart">
                            {{ formData.poster_config.codeDescInfo.titleInfo.content || '这里是活动标题' }}
                        </div>
                        <div
                            v-if="formData.poster_config.codeDescInfo.descInfo.status"
                            ref="desc"
                            :style="{
                                color: formData.poster_config.codeDescInfo.descInfo.color,
                                'font-size': formData.poster_config.codeDescInfo.descInfo.fontSize + 'px',
                                top: formData.poster_config.desc_y + 'px',
                                left: formData.poster_config.desc_x + 'px'
                            }"
                            class="code-desc"
                            @mousedown.stop.capture="moveStart"
                            v-html="handleReplaceDesc(formData.poster_config.codeDescInfo.descInfo.content)" />
                    </div>
                </div>
                <!-- <div class="desc"> 海报尺寸为1080*1920px </div> -->
            </div>
            <div class="btn-box">
                <div>
                    <el-button @click="$e => goBack()">取消</el-button>
                    <el-button :loading="loadingSave" type="primary" @click="saveFun">保存</el-button>
                </div>
            </div>
        </div>

        <ChooseQcode ref="ChooseQcodeRef" @close="closeQcodeBox" @submit="getQcodeFun" />
        <TemplateBox ref="TemplateBoxRef" @save="getTemplateFun" />
    </div>
</template>

<script setup lang="ts">
import { qrcanvas } from 'qrcanvas';
import ChooseQcode from '../components/ChooseQcode.vue';
import TemplateBox from '../components/TemplateBox.vue';
import { nextTick, ref, reactive } from 'vue';
import html2canvas from 'html2canvas';
import { useRoute } from 'vue-router';
import { getGroupList } from '@/api/concreation';
import { createPoster, editPoster, getPosterDetail } from '@/api/highMaterial/poster';
import { ElForm, ElMessage, UploadProps } from 'element-plus';
import { uploadFile2 } from '@/api/common';
import { useStore } from '@/store';

import router from '@/router';
import { get, last, set } from 'lodash';
const ruleFormRef = ref<InstanceType<typeof ElForm>>();
const cascaderRef: any = ref(null); // 选择分组ref
const ChooseQcodeRef = ref(null);
const TemplateBoxRef = ref(null);
const groupData = ref([]);
const route = useRoute();
const store = useStore();
const group_type = route.query.group_type;
const poster_type = route.query.val;
const group_id = Number(route.query.group_id);
/**
 * 预定颜色
 */
const predefineColors = reactive([
    '#C80009',
    '#99004F',
    '#510E93',
    '#0046A7',
    '#006564',
    '#006112',
    '#837800',
    '#FF6B00',
    '#D21F00',
    '#000000',
    '#E70A20',
    '#D8005D',
    '#8414A8',
    '#0079D9',
    '#008B7F',
    '#00912C',
    '#AFB500',
    '#FFA500',
    '#F43C00',
    '#333333',
    '#FF2523',
    '#FF0061',
    '#AA18B8',
    '#009AF8',
    '#009988',
    '#00B342',
    '#CADC00',
    '#FFCD00',
    '#FF4400',
    '#666666',
    '#F9686F',
    '#FF8AB2',
    '#D690DE',
    '#7ECCFD',
    '#64CFC3',
    '#98D8A6',
    '#E6ED92',
    '#FFE481',
    '#FFA595',
    '#999999',
    '#FFCBD2',
    '#FFB8D1',
    '#E9BBEA',
    '#B3E0FB',
    '#A5E2DC',
    '#C0E7C8',
    '#F0F4C0',
    '#FFEFB2',
    '#FFCAB7',
    '#CCCCCC',
    '#FFE9ED',
    '#FFE4EC',
    '#F6E4F6',
    '#DEF3FE',
    '#DCF3F2',
    '#E2F7EB',
    '#FAFBE4',
    '#FFF7DC',
    '#FFE8E9',
    '#FFFFFF'
]);

const validCodeUrl = (rules: any, value: any, callback: any) => {
    if (value) {
        if (!value) {
            callback(new Error('请选择活动二维码'));
        } else {
            callback();
        }
    } else {
        callback();
    }
};

// 校验标题
const validTitleContent = (rules: any, value: any, callback: any) => {
    // 不打开不校验必填
    if (!formData.value.poster_config.codeDescInfo.titleInfo.status) {
        return callback();
    }

    if (!value) {
        return callback(new Error('请输入标题'));
    }
    callback();
};

// 校验描述
const validDescContent = (rules: any, value: any, callback: any) => {
    // 不打开不校验必填
    if (!formData.value.poster_config.codeDescInfo.descInfo.status) {
        return callback();
    }

    if (!value) {
        return callback(new Error('请输入描述'));
    }
    callback();
};
const containerRef = ref<any>(null);
const rules = ref({
    title: { required: true, message: '标题不能为空', trigger: 'blur' },
    group_id: { required: true, message: '请选择分组', trigger: 'change' },
    'poster_config.imgUrl': { required: true, message: '请上传图片', trigger: 'blur' },
    // 'poster_config.codeUrl': { required: true, message: '请选择活动二维码', trigger: 'blur' }
    'poster_config.codeUrl': { validator: validCodeUrl, trigger: 'change' },
    'poster_config.codeDescInfo.titleInfo.content': { validator: validTitleContent },
    'poster_config.codeDescInfo.descInfo.content': { validator: validDescContent }
});
const fontOptions = ref([12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]);
const codeImgUrl = ref('');
// 分组列表
/** 默认的位置 */
const defaultQrcodePostion = {
    x: 250,
    y: 12,
    title_y: 11,
    title_x: 13,
    desc_y: 35,
    desc_x: 14
};
const formData = ref({
    title: '',
    group_id: Number(route.query?.group_id),
    poster_type: route.query.val,
    poster_config: {
        isCodeLink: false, //是否是地址 需要生成二维码
        codeUrl: '', //二维码地址
        imgUrl: '',
        codeStatus: false,
        ...defaultQrcodePostion,
        codeDescInfo: {
            titleInfo: {
                status: false,
                color: '#fff',
                fontSize: 18,
                content: ''
            },
            descInfo: {
                status: false,
                color: '#fff',
                fontSize: 12,
                content: ''
            }
        }
    },
    poster_url_code: ''
});

// 获取海报详情
const getPosterDetailFun = () => {
    getPosterDetail({ poster_id: route.query.id, poster_type: poster_type }).then((r: object) => {
        codeImgUrl.value = r.poster_config.isCodeLink
            ? r.poster_config.codeUrl
            : creatQrCode(
                  r.poster_config.codeUrl.startsWith('http')
                      ? r.poster_config.codeUrl
                      : location.protocol + r.poster_config.codeUrl
              );

        // 给默认值，有的老活动是没有描述和标题的拖拽的
        r.poster_config.desc_x = r.poster_config.desc_x || formData.value.poster_config.desc_x;
        r.poster_config.desc_y = r.poster_config.desc_y || formData.value.poster_config.desc_y;
        r.poster_config.title_x = r.poster_config.title_x || formData.value.poster_config.title_x;
        r.poster_config.title_y = r.poster_config.title_y || formData.value.poster_config.title_y;
        formData.value = Object.assign(formData.value, r);
    });
};
if (route.query.id) {
    getPosterDetailFun();
}

/**
 * 打开switch之前判断是否有图片url
 * 如果没有给出提示并且关闭.switch
 * @param fn 调用的函数
 * @param key 开关的字段
 * @returns {Function} 返回新的校验函数
 */
const withOpenSwitch = (fn: any, key: string) => {
    return function (...arg: any) {
        // 打开的情况下先校验是否有图片url
        if (!formData.value.poster_config.imgUrl && get(formData.value.poster_config, key)) {
            set(formData.value.poster_config, key, false);
            return ElMessage.warning('请先上传图片');
        }
        fn?.call(null, ...arg);
    };
};

const handleChangeSwitch = (key: string) => {
    if (formData.value.poster_config.codeDescInfo[key]?.status) {
        resetElementPostion();
    }
};

/** 长图样式 */
const longImageStyle = {
    'align-self': 'flex-start',
    'margin-top': '35px',
    'margin-bottom': '35px'
};

/** 短图样式 */
const shortImageStyle = {
    'align-self': 'center',
    'margin-top': '0px',
    'margin-bottom': '0px'
};
// 海报壳子样式
const posterBoxStyle = ref<any>({
    'min-height': '620px',
    'align-self': 'center',
    'margin-top': '0px'
});

// 上传海报时处理样式
const handlePosterBackgroundImg = (e: any) => {
    const bgImg = e.target;
    if (!bgImg) {
        return;
    }

    const height = bgImg.getBoundingClientRect().height;

    const phoneContent: any = document.querySelector('.right_container .phone-content') || {};
    if (height < (phoneContent.clientHeight || 0)) {
        posterBoxStyle.value = shortImageStyle;
    } else {
        posterBoxStyle.value = longImageStyle;
    }
    posterBoxStyle.value['min-height'] = height + 'px';
    resetElementPostion?.();
};
// 上传检验
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile: any) => {
    const types = ['jpg', 'jpeg', 'png'];
    if (!types.includes(last(rawFile.name.split('.')))) {
        ElMessage.error('图片格式不正确！');
        return false;
    }
    if (rawFile.size / 1024 / 1024 > 5) {
        formData.value.poster_config.imgUrl = '';
        ElMessage.error('上传图片大小不能超过5M');
        return false;
    }
    uploadFun(rawFile.raw, rawFile.name);
};

// 是否有二维码
const changeQcodeStatusFun = withOpenSwitch((val: boolean) => {
    if (val) {
        ChooseQcodeRef.value.appDialog.visible = true;
    } else {
        formData.value.poster_config.codeUrl = '';
    }
}, 'codeStatus');

// 关闭
const closeQcodeBox = () => {
    if (!formData.value.poster_config.codeUrl) {
        formData.value.poster_config.codeStatus = false;
    }
};

// 生成二维码
const creatQrCode = (data: string) => {
    if (!data) {
        return '';
    }
    return qrcanvas({
        data,
        size: 100
    }).toDataURL('image/png');
};

// 重新选择
const repeatChooseQcode = () => {
    ChooseQcodeRef.value.appDialog.visible = true;
};
// 显示模板的弹框
const showTemplateBox = () => {
    TemplateBoxRef.value.appDialog.visible = true;
};
// 获取模板海报
const getTemplateFun = (val: any) => {
    formData.value.poster_config.imgUrl = val.url;
    formData.value.poster_url_code = val.code;
};

// 获取选择的二维码地址
const getQcodeFun = (val: any) => {
    codeImgUrl.value = val.isCodeUrl
        ? val.url
        : creatQrCode(val.url.startsWith('http') ? val.url : location.protocol + val.url);
    formData.value.poster_config.codeUrl = val.isCodeUrl
        ? val.url
        : val.url.startsWith('http')
        ? val.url
        : location.protocol + val.url;
    formData.value.poster_config.isCodeLink = val.isCodeUrl;
    // 选择完海报校验一次位置
    resetElementPostion();
};

// 返回
const goBack = (flag?: boolean) => {
    const query: any = {
        groupId: Number(route.query.group_id),
        poster_type: formData.value.poster_type
    };
    if (flag) {
        query.groupId = formData.value.group_id;
        store.dispatch('setGroupId', formData.value.group_id);
        store.dispatch('setPosterGroupType', group_type);
        router.push({ path: '/content/highMaterial/poster', query });
    } else {
        router.push({ path: '/content/highMaterial/poster' });
    }
};

/** 禁用保存按钮的loading节流 */
const loadingSave = ref(false);

// 创建海报
const createPosterFun = (param: object) => {
    createPoster(param)
        .then((r: object) => {
            ElMessage.success('创建成功');
            goBack(true);
        })
        .catch(() => {
            loadingSave.value = false;
        });
};

// 编辑
const editPosterFun = (param: object) => {
    editPoster(param)
        .then((r: object) => {
            ElMessage.success('编辑成功');
            goBack(true);
        })
        .catch(() => {
            loadingSave.value = false;
        });
};

// 上传图片的方法
const uploadFun = (file: any, fileName: string, isSubmit = false) => {
    uploadFile2({
        file,
        fileName
    }).then((r: any) => {
        if (isSubmit) {
            formData.value.poster_url_code = r.code;
            const param = JSON.parse(JSON.stringify(formData.value));
            param.poster_config = JSON.stringify(param.poster_config);
            if (route.query.id) {
                param.poster_id = route.query.id;
                editPosterFun(param);
            } else {
                createPosterFun(param);
            }
        } else {
            formData.value.poster_config.imgUrl = r.url || '';
        }
    });
};
// 删除图片
const delFile = () => {
    formData.value.poster_config.imgUrl = '';
    posterBoxStyle.value = shortImageStyle;
    posterBoxStyle.value['min-height'] = '620px';
};

// 保存
const saveFun = () => {
    ruleFormRef.value.validate((valid, fields) => {
        if (valid) {
            loadingSave.value = true;
            convertToImage(document.querySelector('#posterBox')).then((r: any) => {
                uploadFun(r, new Date().getTime() + '.png', true);
            });
        } else {
            ElMessage.error('请填写必填项');
        }
    });
};

const defaultProps = {
    checkStrictly: true,
    emitPath: false,
    label: 'name',
    value: 'id'
};

/**
 * @description 替换描述的左右尖括号，把/n替换成换行
 * @param val
 */
const handleReplaceDesc = (val: string) => {
    const result = val.replace(/\</g, '&lt;').replace(/\>/g, '&gt;').replace(/\n/g, '<br />');
    return result || '这里是活动描述';
};

/**
 * @description 移动时更改当前元素的位置
 * @param {Element} val
 */
const moveStart = (val: any) => {
    const moveCodeX = val.offsetX; // 鼠标当前x，初始x
    const moveCodeY = val.offsetY; // 鼠标当前y，初始y
    // 获取外容器的位置信息-mdn介绍：边界矩形的矩形集合
    const rect: any = document.querySelector('#posterBox')?.getClientRects()[0];

    // 根据外容器的宽高当作最大和最小可移动位置
    const { width: MAX_WIDTH, height: MAX_HEIGHT, left, top } = rect;

    // 默认的字段名（默认判断是移动二维码）
    let x = 'x';
    let y = 'y';

    // title字段名， 如果类名中含有title，代表当前移动的标题，动态绑定title_x和title_y的值
    const isTitle = Array.prototype.includes.call(val.target.classList, 'title');
    if (isTitle) {
        x = 'title_x';
        y = 'title_y';
    }

    // desc字段名， 如果类名中含有code-desc，代表当前移动的标题，动态绑定desc_x和desc_y的值
    const isCodeDesc = Array.prototype.includes.call(val.target.classList, 'code-desc');
    if (isCodeDesc) {
        x = 'desc_x';
        y = 'desc_y';
    }

    // 获取当前移动的元素矩形集合
    const codeRect: any = val.target?.getClientRects()[0];

    // 获取宽高后续用来计算可移动的最大值
    const { width: SELF_WIDTH, height: SELF_HEIGHT } = codeRect;
    // 缓存的xy的值，滚动时会用到
    const handleMove = function (e: any) {
        // 鼠标当前移动的位置 - 外容器的位置 - 初始鼠标位置 = 移动时要给元素设置left或者top的距离
        let configX = e.clientX - left - moveCodeX;
        let configY = e.clientY - top - moveCodeY;
        /**
         * @description 计算可移动的最大值, 最小值是0, 最大值是 外容器的宽高 - 自身的宽高
         * @param number 给元素的left或者top值
         * @param max 最大可移动发距离
         * @param maxAdd 一般来说是当前元素自身的宽高，需要计算最大值使用
         * @param min 最小移动距离。一般都是0
         */
        const getFinalNumber = (number: number, max: number, maxAdd: number, min: number) =>
            number < min ? min : number + maxAdd > max ? max - maxAdd : number;

        // 获取真实left位置
        configX = getFinalNumber(configX, MAX_WIDTH, SELF_WIDTH, 0);
        // 获取真实top位置
        configY = getFinalNumber(configY, MAX_HEIGHT, SELF_HEIGHT, 0);
        formData.value.poster_config[x] = configX;
        formData.value.poster_config[y] = configY;
    };

    document.addEventListener('mousemove', handleMove);
    document.addEventListener('mouseup', () => {
        document.removeEventListener('mousemove', handleMove);
    });
};
const qrcode = ref();
const title = ref();
const desc = ref();
/**
 * 重置元素的定位
 * 会根据当前的位置计算出真实位置防止切换图片后图片位置显示不正确的情况
 */
const resetElementPostion = async () => {
    // 等待dom刷新之后在进行计算
    await nextTick();
    const elementRef = { title, desc, qrcode };

    // 根据外容器的宽高当作最大和最小可移动位置
    const parentWrap: any = document.querySelector('#posterBox');

    const { width: MAX_WIDTH, height: MAX_HEIGHT } = parentWrap.getBoundingClientRect();

    // 可能会遇到没有显示组件的时候。这种情况不处理
    if (!MAX_WIDTH && !MAX_HEIGHT) {
        return;
    }
    for (const [key, refDom] of Object.entries(elementRef)) {
        // 如果当前是关闭状态，则不做处理。
        if (!refDom.value) {
            continue;
        }

        // 默认的字段名（默认判断是移动二维码）
        let x = 'x';
        let y = 'y';

        if (key === 'desc') {
            x = 'desc_x';
            y = 'desc_y';
        }

        if (key === 'title') {
            x = 'title_x';
            y = 'title_y';
        }

        // 获取当前元素的本身宽高,用来做最大和最小的判断
        const { width: SELF_WIDTH, height: SELF_HEIGHT } = refDom.value.getBoundingClientRect();

        /** 校验是否超出了最大位置或者最小位置 */
        const checkFinalNumber = (number: number, max: number, selfSize: number, min: number) => {
            // 当前位置小于最小值 或者 当前位置加上自身的大小 是否 超出最大值
            return number < min || number + selfSize > max;
        };
        // 校验是否超出位置
        const resultX = checkFinalNumber(formData.value.poster_config[x], MAX_WIDTH, SELF_WIDTH, 0);
        // 校验是否超出位置
        const resultY = checkFinalNumber(formData.value.poster_config[y], MAX_HEIGHT, SELF_HEIGHT, 0);

        if (resultX || resultY) {
            formData.value.poster_config[x] = defaultQrcodePostion[x];
            formData.value.poster_config[y] = defaultQrcodePostion[y];
        }
    }
};

// 获取分组列表详情
const getGroup = () => {
    getGroupList({
        type: group_type
    }).then((res: any) => {
        groupData.value = res.data;
    });
};
getGroup();
// 选择完地区后立即关闭
const orgChange = () => {
    cascaderRef.value.togglePopperVisible();
};

// 合成图片的方法
const convertToImage = async (container: any) => {
    const { width, height } = container.getClientRects()[0];

    const scale = 4;
    const ops: any = { scale, width, height, useCORS: true };
    const canvasImg = await html2canvas(container, ops);
    return new Promise(resolve => {
        canvasImg.toBlob((blob: any) => {
            resolve(blob);
        }, 'image/png');
    });
};
</script>

<style lang="scss" scoped>
.layout {
    display: flex;
    justify-content: flex-start;
    overflow-y: hidden;
    height: calc(100vh - 142px) !important;

    .left_container {
        width: 378px;
        margin-right: 16px;
        border: 1px solid #eaeaea;
        padding: 0 16px 30px;
        overflow-y: auto;
        background-color: #fff;

        .title {
            font-size: 16px;
            font-family: STHeitiSC-Medium, STHeitiSC;
            font-weight: 500;
            color: #33302d;
            padding-top: 20px;
            margin-bottom: 20px;

            &.active {
                border-top: solid 1px #eaeaea;
            }
        }

        .upload-content {
            .upload-box {
                width: 110px;
                height: 110px;
                text-align: center;
                border-radius: 4px;
                background: #f8f8f8;
                border: 1px solid #eaeaea;
                box-sizing: border-box;
                padding-top: 28px;

                img {
                    width: 20px;
                    height: 20px;
                }

                div {
                    width: 100%;
                    line-height: 14px;
                    font-size: 14px;
                    font-family: STHeitiSC-Light, STHeitiSC;
                    color: #ff6b00;
                }
            }

            .upload-file-box {
                position: relative;
                width: 110px;
                height: 110px;
                border-radius: 4px;
                border: 1px solid #eaeaea;
                overflow: hidden;
                cursor: pointer;

                .del {
                    z-index: 2;
                    display: none;
                    position: absolute;
                    left: 50%;
                    top: 50%;
                    transform: translate(-50%, -50%);
                }

                &:hover {
                    .del {
                        display: block;
                    }

                    &::after {
                        content: '';
                        background: rgb(0 0 0 / 50%);
                        position: absolute;
                        inset: 0;
                    }
                }
            }

            .upload-text {
                padding-top: 16px;
                line-height: 1.4;
                font-size: 12px;
                color: #999;
            }

            .upload-desc {
                font-size: 14px;
                font-family: STHeitiSC-Light, STHeitiSC;
                font-weight: 300;
                color: #969696;

                // padding-top: 10px;
                span {
                    color: #ff6b00;
                    cursor: pointer;
                }
            }
        }

        .code-choose-btn {
            margin-left: 18px;
            margin-bottom: 22px;
        }

        .codeText-set-box {
            font-size: 14px;
            font-family: STHeitiSC-Light, STHeitiSC;
            font-weight: 300;
            color: #33302d;
            display: flex;
            margin-left: 21px;
            align-items: center;
            margin-bottom: 22px;

            span {
                margin-right: 10px;
            }

            span:last-of-type {
                margin-left: 45px;
            }
        }
    }

    .right_container {
        display: flex;
        -webkit-box-orient: vertical;
        width: calc(100% - 394px);
        background-color: #fff;
        height: 99.9%;
        border: solid 1px #eaeaea;
        flex-direction: column;

        .phone-content {
            width: 100%;
            flex: 1;
            display: flex;
            justify-content: center;
            overflow: auto;
        }

        .poster-box {
            width: 360px;
            outline: 1px solid #eaeaea;
            position: relative;

            .poster-item {
                z-index: 100;

                .posterImg {
                    width: 100%;
                    height: 100%;
                    z-index: 1;
                    position: relative;
                    display: block;
                }

                &.hideBox {
                    position: absolute;
                    width: 100%;
                    height: 100%;
                    z-index: 10;
                    top: 0;
                    left: 0;
                }

                .backgroundImg {
                    user-select: none;
                    pointer-events: none;
                }

                user-select: none;
                position: relative;
                overflow: hidden;
                width: 100%;
                height: 100%;

                .code-box {
                    display: inline-block;
                    position: absolute;
                    width: 100px;
                    height: 100px;
                    bottom: 16px;
                    left: 16px;
                    cursor: move;

                    // width: calc(100% - 16px);
                    z-index: 9;

                    img {
                        display: block;
                        width: 100px;
                        height: 100px;
                        pointer-events: none;
                        user-select: none;
                    }
                }

                .title {
                    cursor: move;
                    position: absolute;
                    font-size: 18px;
                    font-weight: 500;
                    color: #fff;
                    margin-bottom: 8px;
                    z-index: 1;
                }

                .code-desc {
                    cursor: move;
                    position: absolute;
                    font-size: 12px;
                    font-weight: 500;
                    color: #fff;
                    line-height: calc(1em + 6px);
                    z-index: 1;
                }

                .move_icon {
                    cursor: move;
                }
            }

            .upload-box {
                width: 348px;
                height: 620px;
                position: relative;
                display: flex;
                justify-content: center;
                align-items: center;
                flex-wrap: wrap;

                div {
                    width: 100%;
                    font-size: 28px;
                    font-family: STHeitiSC-Light, STHeitiSC;
                    font-weight: 300;
                    color: #ff6b00;
                    line-height: 29px;
                    padding-top: 21px;
                    text-align: center;
                }

                .mode-text {
                    width: 94%;
                    padding-top: 16px;
                    line-height: 1.4;
                    font-size: 12px;
                    color: #999;
                }

                .mode-desc {
                    width: 100%;
                    text-align: center;
                    font-size: 14px;
                    font-family: STHeitiSC-Light, STHeitiSC;
                    font-weight: 300;
                    color: #33302d;
                    padding-top: 0;
                    position: absolute;
                    bottom: 16px;
                    left: 0;
                    z-index: 9;

                    span {
                        color: #ff6b00;
                        cursor: pointer;
                    }
                }
            }
        }

        .desc {
            text-align: center;
            font-size: 14px;
            font-family: STHeitiSC-Light, STHeitiSC;
            font-weight: 300;
            color: #33302d;
            margin-bottom: 34px;
        }

        .btn-box {
            border-top: 1px solid #d9d9d9;
            border-bottom: 1px solid #d9d9d9;
            padding: 11px 24px;
            text-align: center;
            display: flex;
            flex-direction: column;
        }
    }

    .config-label {
        font-size: var(--el-form-label-font-size);
        color: var(--el-text-color-regular);
        height: 32px;
        line-height: 32px;
        font-weight: 400;
        font-family: 'PingFang SC';
    }
}

:global(.poster-setting-color-picker .el-color-predefine__color-selector > div) {
    outline: #e9e9e9 solid 1px;
}
</style>

<style lang="scss">
.codeLabel {
    .el-form-item__label {
        width: 100px !important;
    }
}

.codeDescLabel {
    .el-form-item__label {
        width: 60px !important;
    }
}

.poster-setting-color-picker {
    .el-color-dropdown__btns {
        .el-button.is-plain {
            color: #ff6b00;
            border-color: #ff6b00;

            &:hover {
                color: #fff;
                background-color: #ff6b00;
            }
        }
    }
}
</style>
